package com.fasteat.search.controller;

import com.fasteat.common.entity.Result;
import com.fasteat.search.entity.SearchCondition;
import com.fasteat.search.service.MallProductSearchService;
import com.fasteat.search.util.SearchUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/search/mall")
@Api(tags = "商品搜索模块")
@CrossOrigin
public class MallProductSearchController {

	@Autowired
	private MallProductSearchService mallProductSearchService;


	@PostMapping
	@ApiOperation("分页高亮默认方式搜索商品（供远程调用）")
	public Result searchProductWithHighlightAndPage(@RequestBody @ApiParam(value = "搜索条件") SearchCondition condition) {
		if (condition == null
				|| condition.getEntry() == null
				|| condition.getEntry().size() == 0) {
			return Result.error("查询失败");
		}
		return Result.success().data(mallProductSearchService.searchWithHighlightAndPageAndSort(condition, null));
	}


	@PostMapping("/{salesVolumeSort}/{priceSort}/{timeSort}")
	@ApiOperation("分页高亮带排序搜索商品（供远程调用）")
	public Result searchProductWithHighlightAndPageAndSort(@RequestBody @ApiParam(value = "搜索条件") SearchCondition condition,
														   @PathVariable(name = "salesVolumeSort") @ApiParam(required = true, value = "0、默认方式，1、销量升序，2、销量降序") int salesVolumeSort,
														   @PathVariable(name = "priceSort") @ApiParam(required = true, value = "0、默认方式，1、价格升序，2、价格降序") int priceSort,
														   @PathVariable(name = "timeSort") @ApiParam(required = true, value = "0、默认方式，1、时间升序，2、时间降序") int timeSort) {
		if (condition == null
				|| condition.getEntry() == null
				|| condition.getEntry().size() == 0) {
			return Result.error("查询失败");
		}
		Map<String, SortOrder> sortMap = new HashMap<>(3);
		SearchUtil.setSortType(sortMap, "sales_volume", salesVolumeSort);
		SearchUtil.setSortType(sortMap, "sale_price", priceSort);
		SearchUtil.setSortType(sortMap, "gmt_create.keyword", timeSort);
		return Result.success().data(mallProductSearchService.searchWithHighlightAndPageAndSort(condition, sortMap));
	}

	@DeleteMapping("/{id}")
	@ApiOperation("通过id删除商品（供远程调用）")
	public Result deleteProductById(@PathVariable(name = "id") String id) {
		if (StringUtils.isEmpty(id)) {
			return Result.error("删除失败");
		}
		return mallProductSearchService.removeProductById(id) ? Result.success("删除成功") : Result.error("删除失败");
	}

}
